/**
 * @author:albert
 */

package com.bkbw.live.battle.business;

import java.util.HashMap;
import java.util.LinkedList;

// 在地图的update中，对象可能创建对象，也可能消除对象，然而在遍历collection时增加和删除元素可能引发ConcurrentModificationException
// 也就是说需要把要增加和删除的对象先单独保存一份，待遍历完毕后再加入，这个类就是做这个用途的
public class GameHashMap<V extends GameObject> extends HashMap<Integer, V>{
	private static final long serialVersionUID = 4792835916866197270L;
	
	protected HashMap<Integer, V> addList = new HashMap<Integer, V>();
	protected HashMap<Integer, V> removeList = new HashMap<Integer, V>();
	
	public void prepareToAdd(V value) {
		//addList.add(value);
		addList.put(value.getId(), value);
	}
	
	public void prepareToRemove(V value) {
		//removeList.add(value);
		removeList.put(value.getId(), value);
	}
	
	public void commit() {
		for (V value : addList.values()) {
			put(value.getId(), value);
		}
		addList.clear();
		
		for (V gameObject : removeList.values()) {
			remove(gameObject.getId());
		}
		removeList.clear();
	}
	
	@Override
	public boolean containsKey(Object key) {
		if (super.containsKey(key)){
			return true;
		}
		return addList.containsKey(key);
	}
}
